package scoutobahn.xml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.LinkedList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import scoutobahn.xml.automaton.OsmItemStreamManager;
import scoutobahn.xml.automaton.OsmSaxHandler;
/**
 * Class to load a list OsmNodes representing towns from an osm xml file.
 * @author mark
 *
 */
public class XmlTownLoader implements OsmItemStreamManager {

    private Collection<OsmNode> nodes;
    /**
     * Reads all OsmNodes from given InputStream.
     * @param inStream The stream to the xml content
     * @return A list of all OsmNode
     * @throws ParserConfigurationException Something bad happens
     * @throws SAXException Something bad happens
     * @throws IOException Can't read the InputStream
     */
    public Collection<OsmNode> loadTowns(final InputStream inStream)
            throws ParserConfigurationException, SAXException, IOException {
        this.nodes = new LinkedList<OsmNode>();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(new OsmSaxHandler(this));
        xmlReader.parse(new InputSource(inStream));
        inStream.close();
        return this.nodes;
    }
    @Override
    public void nodeFound(final OsmNode node) {
        this.nodes.add(node);
    }

    @Override
    public void relationFound(final OsmRelation relation) { }

    @Override
    public void wayFound(final OsmWay way) { }

    @Override
    public OsmItemProvider getProvider() {
        return null;
    }

}
